//
//  BSLWebView.m
//  demo
//
//  Created by RYAN on 15/8/4.
//
//

#import "BSLWebView.h"

#define kMaxLeftOfRightSlider 255
#define kScaleMin 0.05
#define kScaleOrigin 1.0

NSString *const BSLWebViewDidDismissNotification = @"BSLWebViewDidDismissNotification";
NSString *const BSLWebViewDidShowNotification = @"BSLWebViewDidShowNotification";
NSString *const BSLWebViewDidHideNotification = @"BSLWebViewDidHideNotification";
NSString *const BSLWebViewDidCloseNotification = @"BSLWebViewDidCloseNotification";
NSString *const BSLWebViewDidLoadedNotification = @"BSLWebViewDidLoadedNotification";

@interface BSLWebView ()

@property (nonatomic, strong) UIPanGestureRecognizer *panGesture;
@property (nonatomic, assign) CGFloat panGestureBeginOffsetX;
@property (nonatomic, assign) CGFloat screenWidth;
@property (nonatomic, assign) CGFloat screenHeight;
@property (nonatomic, strong) NSString *lastShowAnimation;
@property (nonatomic, strong) NSString *lastHideAnimation;
@property (nonatomic, strong) NSString *lastCloseAnimation;

@end

@implementation BSLWebView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.screenWidth = [UIScreen mainScreen].bounds.size.width;
        self.screenHeight = [UIScreen mainScreen].bounds.size.height;
        self.lastShowAnimation = @"none";
        self.lastHideAnimation = @"none";
        self.lastCloseAnimation = @"none";
    }
    
    return self;
}

- (void)setStyle:(NSDictionary *)styles{
    if ((NSNull *)styles != [NSNull null]) {
        if ([styles objectForKey:@"background"]) {
            [self setupBackgroundColor:[styles objectForKey:@"background"]];
        }
        
        if ([styles objectForKey:@"top"] || [styles objectForKey:@"bottom"] || [styles objectForKey:@"left"] || [styles objectForKey:@"right"] ||
            [styles objectForKey:@"width"] || [styles objectForKey:@"height"]) {
            [self setupFrame:styles];
        }
        
        if ([styles objectForKey:@"bounce"]) {
            BOOL bounce = [[styles objectForKey:@"bounce"] boolValue];
            [self.scrollView setBounces:bounce];
            self.shouldBounces = bounce;
        }
        
        if ([styles objectForKey:@"bounceBackground"]) {
            NSString *bounceBg = [styles objectForKey:@"bounceBackground"];
            BOOL bounce = self.scrollView.bounces;
            
            if (bounceBg.length && bounce) {
                [self setupBounceBg:bounceBg];
            }
        }
        
        self.mask = [styles objectForKey:@"mask"];
        if ([styles objectForKey:@"margin"]) {
            //            _marginStyle = [[NSString alloc] initWithString:[styles objectForKey:@"margin"]];
        }
        
        if ([styles objectForKey:@"opacity"]) {
            NSNumber *opacity = [styles objectForKey:@"opacity"];
            if (opacity) {
                [self setOpacity:[opacity boolValue]];
            }
        }
        
        if ([styles objectForKey:@"popGesture"]) {
            //设置手势滑动的方法，当需要在width=‘100%’才有效
            [self setPopGesture:[styles objectForKey:@"popGesture"]];
        }
        
        if ([styles objectForKey:@"scalable"]){
            BOOL shouleScalable = [[styles objectForKey:@"scalable"] boolValue];
            [self setShouldScale:shouleScalable];
        }
        
        if ([styles objectForKey:@"scrollIndicator"]) {
            [self setIndicator:[styles objectForKey:@"scrollIndicator"]];
        }
        
        if ([styles objectForKey:@"scrollsToTop"]) {
            BOOL shouldToTop = [[styles objectForKey:@"scrollsToTop"] boolValue];
            [self setScrollToTop:shouldToTop];
        }
        
        if ([styles objectForKey:@"softinputMode"]) {
            
        }
        
        //        if ([styles objectForKey:@"zindex"]){
        //            int zindex = [[styles objectForKey:@"zindex"] intValue];
        //            [self setZindex:zindex];
        //        }
    }
}

- (void)setupFrame:(NSDictionary *)parm{
    NSString *topStr = [parm objectForKey:@"top"];
    NSString *bottomStr = [parm objectForKey:@"bottom"];
    NSString *leftStr = [parm objectForKey:@"left"];
    NSString *rightStr = [parm objectForKey:@"right"];
    NSString *widthStr = [parm objectForKey:@"width"];
    NSString *heightStr = [parm objectForKey:@"height"];
    
    CGFloat(^coordinateFromString)(NSString *string,BOOL isHorizontal);
    coordinateFromString = ^(NSString *string,BOOL isHorizontal){
        CGFloat result = 0;
        if (!string) {
            return result;
        }
        
        NSRange range = [string rangeOfString:@"%"];
        if (range.location >0 && range.length) {
            NSString *temp = [string substringWithRange:NSMakeRange(0, range.location)];
            result = [temp floatValue];
            CGFloat size = (isHorizontal) ? [UIScreen mainScreen].bounds.size.width : [UIScreen mainScreen].bounds.size.height;
            result = result * size / 100.0;
        }
        
        else{
            result = [string floatValue];
        }
        
        return result;
    };
    //设置Y
    if ( [topStr isKindOfClass:[NSString class]] && topStr.length) {
        CGFloat top = coordinateFromString(topStr,NO);
        self.top = top;
    }
    
    if (heightStr.length) {
        CGFloat height = coordinateFromString(heightStr,NO);
        self.height = height;
    }
    
    if (bottomStr.length && (!topStr.length || !heightStr.length)) {
        CGFloat bottom = coordinateFromString(bottomStr,NO);
        if (topStr.length) {
            CGFloat top = coordinateFromString(topStr,NO);
            self.height = bottom - top;
        }
        
        if (heightStr.length){
            CGFloat height = coordinateFromString(heightStr,NO);
            self.height = height;
        }
        
        self.bottom = bottom;
    }
    
    //设置X
    if ([leftStr isKindOfClass:[NSString class]] && leftStr.length){
        CGFloat left = coordinateFromString(leftStr,YES);
        self.left = left;
    }
    
    if (widthStr.length){
        CGFloat width = coordinateFromString(widthStr,YES);
        self.width = width;
    }
    
    if (rightStr.length && (!leftStr.length || !widthStr.length)){
        CGFloat right = coordinateFromString(rightStr,YES);
        if (leftStr.length) {
            CGFloat left = coordinateFromString(leftStr,YES);
            CGFloat width = right - left;
            self.width = width;
        }
        
        if (widthStr.length) {
            CGFloat width = coordinateFromString(widthStr,YES);
            self.width = width;
        }
        
        self.right = right;
    }
    
    //margin
    if (topStr.length && bottomStr.length && rightStr.length && leftStr.length) {
        //        _shouldMargin = NO;
    }
}

- (void)setupBounceBg:(NSString *)bounceBackgroundCode{
    UIImageView *iv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, K_DEFAULT_BOUNCE_BG_HEIGHT)];
    iv.bottom = 0;
    iv.contentMode = UIViewContentModeScaleAspectFill;
    iv.clipsToBounds = YES;
    iv.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.bounceBackgroundView = iv;
    
    [self.scrollView addSubview:self.bounceBackgroundView];
    //    self.scrollView.delegate = self;
    
    NSRange range = [bounceBackgroundCode rangeOfString:@"url("];
    if (range.location != NSNotFound && range.length) {
        NSUInteger start = range.location + range.length;
        range = [bounceBackgroundCode rangeOfString:@")"];
        NSUInteger end = range.location;
        
        NSString *pathStr = [bounceBackgroundCode substringWithRange:NSMakeRange(start, end - start)];
        NSArray *array = [pathStr componentsSeparatedByString:@"."];
        NSString *sufix = [array objectAtIndex:1];
        NSString *subPathStr = [array objectAtIndex:0];
        range = [subPathStr rangeOfString:@"/" options:NSBackwardsSearch];
        NSString *fileName = [subPathStr substringFromIndex:range.location+1];
        NSString *directory = [subPathStr substringToIndex:range.location];
        
        NSString *imgPath = [[NSBundle mainBundle] pathForResource:fileName ofType:sufix inDirectory:directory];
        UIImage *img = [UIImage imageWithContentsOfFile:imgPath];
        [self.bounceBackgroundView setImage:img];
    }
    
    else{
        UIColor *color = [UIColor colorWithHexString:bounceBackgroundCode];
        [iv setBackgroundColor:color];
    }
}

- (void)setupBackgroundColor:(NSString *)colorCode{
    NSRange range = [colorCode rangeOfString:@"#"];
    UIColor *color = [UIColor whiteColor];//default
    
    if (range.location != NSNotFound && range.length) {
        color = [UIColor colorWithHexString:colorCode];
    }
    
    else if(range.location == NSNotFound){
        range = [colorCode rangeOfString:@"rgba" options:NSCaseInsensitiveSearch];
        if (range.location != NSNotFound) {
            color = [UIColor colorWithRGBAValue:colorCode];
        }
        
        else{
            range = [colorCode rangeOfString:@"rgb" options:NSCaseInsensitiveSearch];
            if (range.location != NSNotFound) {
                color = [UIColor colorWithRGBValue:colorCode];
            }
        }
    }
    
    [self.scrollView setBackgroundColor:color];
    [self setOpaque:NO];
    
    NSArray *views = [[self scrollView] subviews];
    for (UIView *v in views) {
        if ([NSStringFromClass([v class]) hasPrefix:@"UIWebBrowserView"]) {
            self.browserView = v;
            break;
        }
    }
    
    [self.browserView setHidden:YES];
}


- (void)setMask:(NSString *)mask{
    if (_mask != mask) {
        _mask = mask;

        if ([_mask isEqualToString:@"none"]) {
            if (self.maskView) {
                [self.maskView removeFromSuperview];
                self.maskView = nil;
            }
        }

        else{
            UIColor *color = [UIColor colorWithRGBAValue:mask];
            if (!self.maskView) {
                self.maskView = [[MaskView alloc] initWithFrame:self.bounds];
            }

            [self.maskView setBackgroundColor:color];
            [self addSubview:self.maskView];
        }
    }
}

- (void)setPopGesture:(NSString *)popGesture{
    
    if (([popGesture isEqualToString:@"hide"] || [popGesture isEqualToString:@"close"])) {
        if (!self.panGesture) {
            UIPanGestureRecognizer *gesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGesture:)];
            [gesture setMaximumNumberOfTouches:1];
            [gesture setMinimumNumberOfTouches:1];
            
            [self addGestureRecognizer:gesture];
            self.panGesture = gesture;

        }
        
        self.shouldHide = ([popGesture isEqualToString:@"hide"]) ? YES : NO;
    }
    
    else if ([popGesture isEqualToString:@"none"]){
        [self removeGestureRecognizer:self.panGesture];
        self.panGesture = nil;
    }
}

- (void)handlePanGesture:(UIPanGestureRecognizer *)recognizer{
    
    CGPoint translatedPoint = [recognizer translationInView:self];
    if (recognizer.state == UIGestureRecognizerStateBegan)
    {
        self.panGestureBeginOffsetX = self.left;
    }
    
    else if (recognizer.state == UIGestureRecognizerStateChanged){
        self.left = MAX(translatedPoint.x + self.panGestureBeginOffsetX, self.panGestureBeginOffsetX);
    }
    
    else{
        CGPoint velocity = [recognizer velocityInView:self];
        BOOL toLeft;
        NSTimeInterval duration = 0.2;
        if (fabs(velocity.x) > 1000) {
            toLeft = velocity.x < 0;
            if (toLeft) {
                duration = - self.left / velocity.x;
            }
            
            else{
                duration = (kMaxLeftOfRightSlider - self.left) / velocity.x;
            }
        }
        
        else{
                toLeft = self.left < kMaxLeftOfRightSlider / 2.0;
        }
        
        [UIView animateWithDuration:duration animations:^{
            self.left = toLeft ? self.panGestureBeginOffsetX : self.screenWidth;
        } completion:^(BOOL finished) {
            if (self.left == self.screenWidth) {
                if (self.shouldHide) {
                    [self setHidden:YES];
                    return ;
                }
                
                [self removeFromSuperview];
                [[NSNotificationCenter defaultCenter] postNotificationName:BSLWebViewDidDismissNotification object:self];
            }
        }];
    }
}

- (void)setIndicator:(NSString *)indicator{
    BOOL horizontalIndicator = YES;
    BOOL verticalIndicator = YES;
    
    if ([indicator isEqualToString:@"vertical"]){
        horizontalIndicator = NO;
    }
    
    else if ([indicator isEqualToString:@"horizontal"]){
        verticalIndicator = NO;
    }
    
    else if ([indicator isEqualToString:@"none"]){
        verticalIndicator = NO;
        horizontalIndicator = NO;
    }
    
    [self.scrollView setShowsHorizontalScrollIndicator:horizontalIndicator];
    [self.scrollView setShowsVerticalScrollIndicator:verticalIndicator];
}

- (void)setScrollToTop:(BOOL)shouldScrollToTop{
    [self.scrollView setScrollsToTop:shouldScrollToTop];
}

- (void)animationDidStart:(CAAnimation *)anim{
    
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    if (flag) {
//        [self setHidden:YES];
    }
}
@end
